#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAXDATA_LEN 8192
typedef struct package {
    char data[MAXDATA_LEN];
    int  len;
} Package;
int main()
{
    int sockfd, ret;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sockfd) {
        perror("socket");
        return -1;
    }
    printf("socket create success\n");
    //客户端可以不用绑定(如果需要固定端口就要绑定)

    // inter协议族
    struct sockaddr_in connectaddr, clientadrr;
    clientadrr.sin_family  = AF_INET;
    connectaddr.sin_family = AF_INET;
    //客户端和服务端的端口号必须相等
    connectaddr.sin_port = htons(7777);
    clientadrr.sin_port  = htons(9999);
    // ip地址为服务器的ip地址
    connectaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
    // clientadrr.sin_addr.s_addr = inet_addr("0");
    connectaddr.sin_addr.s_addr = inet_addr("0");
    //客户端可以不绑定，系统会随机分配端口
    // ret = bind(sockfd, (struct sockaddr*)&clientadrr, sizeof(clientadrr));
    ret = connect(sockfd, (struct sockaddr*)&connectaddr, sizeof(connectaddr));
    /**
     * @description:向服务器发起连接
     * @param
     * {*}第一个参数：套接字，第二个参数：指向sockaddr的指针，第三个参数：sockaddr结构体大小
     * @return {*}成功返回0，失败返回-1；
     */
    if(-1 == ret) {
        perror("connect:");
        return -1;
    }
    printf("connect success\n");
    char    buf[128] = "12345";
    Package pack;
    // Package *pack ;

    pack.len = 11;
    while(1) {
        sleep(1);
        // strcpy(pack.data,"hello world");
        // int ret = write(sockfd, buf, strlen(buf));
        int ret = recv(sockfd, &pack, sizeof(pack), 0);
        if(-1 == ret) {
            perror("read");
            // free(pack.data);
            return -1;
        }
        if(0 == ret) { break; }
        printf("%d\n %s\n", pack.len, pack.data);
        memset(&pack, 0, sizeof(package));
    }
    printf("end\n");
    close(sockfd);
    return 0;
}
